
import { getToken as token } from '@/utils/auth'
import store from '@/store'
import ReconnectingWebSocket from 'reconnecting-websocket';
import MR from './messageRegister';

const socketPath = "ws://" + process.env.VUE_APP_SOCKET_API

let websocket;
function init(userId) {
	if(!WebSocket){
		this.msgError('当前浏览器版本过低，部分功能无法使用!',3);
		return;
	}
	websocket = new ReconnectingWebSocket(socketPath+getToken());
	websocket.addEventListener('open', (evt) => {
		console.log('connected websocket server ~');
	});
	websocket.addEventListener('close', (evt) => {
    console.log('close websocket server ~');
	});
	websocket.addEventListener('message', (evt) => {
		let result = JSON.parse(evt.data);
		MR.call(result);
	});
	websocket.addEventListener('error', (evt) => {
    console.log('socket has error');
	});
}

function getToken() {
	let _token = token();
	_token=_token?_token:'';
	_token='Bearer '+_token;
	_token= '?Authorization='+_token;
	_token+=('&userId='+ `${store.state.user.name}` );
	_token+=('&client=PC');
	return _token;
}

function send(message) {
	if(!websocket){
		app.log.error('The current browser does not support websocket!');
		return;
	}
	websocket.send(message);

}
function close() {
	if(websocket){
		websocket.close();
	}
}

export default {
	init,send,close
}
